package com.ruoyi.ruoyiqywechat.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.qy.common.MyRecord;
import com.ruoyi.common.qy.constants.Constants;
import com.ruoyi.common.qy.constants.SysConfigConstants;
import com.ruoyi.common.qy.domain.User;
import com.ruoyi.common.qy.exception.CrmebException;
import com.ruoyi.common.qy.request.PreOrderRequest;
import com.ruoyi.common.qy.response.PreOrderResponse;
import com.ruoyi.common.qy.utils.CrmebUtil;
import com.ruoyi.common.qy.vo.OrderInfoVo;
import com.ruoyi.common.redis.utils.RedisUtil;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ruoyiqywechat.domain.MembershipPlanNew;
import com.ruoyi.ruoyiqywechat.domain.UserMembership;
import com.ruoyi.ruoyiqywechat.service.IMembershipPlanNewService;
import com.ruoyi.ruoyiqywechat.service.IUserMembershipService;
import com.ruoyi.ruoyiqywechat.service.SystemConfigService;
import com.ruoyi.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ruoyiqywechat.mapper.OrderQyMapper;
import com.ruoyi.ruoyiqywechat.domain.OrderQy;
import com.ruoyi.ruoyiqywechat.service.IOrderQyService;

/**
 * 订单Service业务层处理
 *
 * @author 好六
 * @date 2025-10-10
 */
@Service
public class OrderQyServiceImpl implements IOrderQyService
{
    @Autowired
    private OrderQyMapper orderQyMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SystemConfigService systemConfigService;
    /**
     * 订单预下单
     *
     * @param request 预下单请求参数
     * @return PreOrderResponse
     */
    @Override
    public MyRecord preOrder(PreOrderRequest request) {
        // 缓存订单
        String key = SecurityUtils.getUserId() + DateUtils.getNowDate().getTime() + CrmebUtil.getUuid();
        redisUtil.set("user_order:" + key, JSONObject.toJSONString(request), Constants.ORDER_CASH_CONFIRM, TimeUnit.MINUTES);
        MyRecord record = new MyRecord();
        record.set("preOrderNo", key);
        return record;
    }
    /**
     * 加载预下单信息
     *
     * @param preOrderNo 预下单号
     * @return 预下单信息
     */
    @Override
    public PreOrderResponse loadPreOrder(String preOrderNo) {
        // 通过缓存获取预下单对象
        String key = "user_order:" + preOrderNo;
        boolean exists = redisUtil.exists(key);
        if (!exists) {
            throw new CrmebException("预下单订单不存在");
        }
        String orderVoString = redisUtil.get(key).toString();
        PreOrderRequest request = JSONObject.parseObject(orderVoString, PreOrderRequest.class);
        PreOrderResponse preOrderResponse = new PreOrderResponse();
        preOrderResponse.setPreOrderRequest(request);
        String payWeixinOpen = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_PAY_WEIXIN_OPEN);
        String yuePayStatus = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_YUE_PAY_STATUS);// 1开启 2关闭
        String storeSelfMention = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_KEY_STORE_SELF_MENTION);
        String aliPayStatus = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_ALI_PAY_STATUS);// 1开启
        preOrderResponse.setYuePayStatus(yuePayStatus);
        preOrderResponse.setPayWeixinOpen(payWeixinOpen);
        preOrderResponse.setStoreSelfMention(storeSelfMention);
        preOrderResponse.setAliPayStatus(aliPayStatus);
        return preOrderResponse;
    }
    @Autowired
    private IMembershipPlanNewService membershipPlanNewService;

    @Autowired
    private IUserMembershipService userMembershipService;
    /**
     * 创建订单
     *
     * @param preOrderNo 创建订单请求参数
     * @return MyRecord 订单编号
     */
    @Override
    public MyRecord createOrder(String preOrderNo) {
        Claims claims = JwtUtils.parseToken(SecurityUtils.getToken());
        String userid = JwtUtils.getUserId(claims);
        if(userid == null)throw new  CrmebException("用户不存在!");
        // 通过缓存获取预下单对象
        String key = "user_order:" + preOrderNo;
        boolean exists = redisUtil.exists(key);
        if (!exists) {
            throw new CrmebException("预下单订单不存在");
        }
        String orderVoString = redisUtil.get(key).toString();
        PreOrderRequest preOrderRequest = JSONObject.parseObject(orderVoString, PreOrderRequest.class);
        // 生成订单号
        String orderNo = CrmebUtil.getOrderNo("order");


        MembershipPlanNew membershipPlanNew = membershipPlanNewService.selectMembershipPlanNewById(preOrderRequest.getMemberPlanNewId());
        //判断当前会员是否重复，如果是则不允许重复会员充值
        QueryWrapper<UserMembership> userMembershipQueryWrapper = new QueryWrapper<>();
        userMembershipQueryWrapper.lambda().eq(UserMembership::getUserId,userid)
                                .eq(UserMembership::getStatus,1);
        UserMembership one = userMembershipService.getOne(userMembershipQueryWrapper);
        if(one != null){
            throw new CrmebException("会员未到期!");
        }

        OrderQy orderQy = new OrderQy();
        orderQy.setOrderNo(orderNo);
        orderQy.setPlanId(preOrderRequest.getMemberPlanNewId());
        orderQy.setUserId(Long.valueOf(userid));
        orderQy.setStatus(0);
        orderQy.setAmount(membershipPlanNew.getPrice());
        orderQy.setPayChannel("wechat");

        orderQyMapper.insertOrderQy(orderQy);

        // 删除缓存订单
        if (redisUtil.exists(key)) {
            boolean l = redisUtil.delRemove(key);
            System.out.println("是否移除成功："+l);
        }
        // 加入自动未支付自动取消队列
        redisUtil.lPush(Constants.ORDER_AUTO_CANCEL_KEY, orderQy.getOrderNo());
        MyRecord record = new MyRecord();
        record.set("orderNo", orderQy.getOrderNo());
        return record;
    }
    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderQy selectOrderQyById(Long id)
    {
        return orderQyMapper.selectOrderQyById(id);
    }

    /**
     * 查询订单列表
     *
     * @param orderQy 订单
     * @return 订单
     */
    @Override
    public List<OrderQy> selectOrderQyList(OrderQy orderQy)
    {
        return orderQyMapper.selectOrderQyList(orderQy);
    }

    /**
     * 新增订单
     *
     * @param orderQy 订单
     * @return 结果
     */
    @Override
    public int insertOrderQy(OrderQy orderQy)
    {
        orderQy.setCreateTime(DateUtils.getNowDate());
        return orderQyMapper.insertOrderQy(orderQy);
    }

    /**
     * 修改订单
     *
     * @param orderQy 订单
     * @return 结果
     */
    @Override
    public int updateOrderQy(OrderQy orderQy)
    {
        orderQy.setUpdateTime(DateUtils.getNowDate());
        return orderQyMapper.updateOrderQy(orderQy);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderQyByIds(Long[] ids)
    {
        return orderQyMapper.deleteOrderQyByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderQyById(Long id)
    {
        return orderQyMapper.deleteOrderQyById(id);
    }



}
